import logging

from django.core.exceptions import ValidationError
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema, OpenApiExample, OpenApiParameter
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import json
from app.services.user_service import UserService
from datetime import datetime

from app.models import User, Employee, OrderItem, Order
from app.models import (
    User, MerchantInfo, Employee, Attendance, EmployeeActivity,MerchantInfo,
    LeaveRequest, PerformanceRecord, SalaryRecord, OrderItem, Order, Dish, Category
)
from django.utils import timezone
from middleware.util import make_response
logger = logging.getLogger('app')
@extend_schema(
    tags=['用户模块'],
    summary='用户登录',
    description='通过用户名和密码进行登录，返回 JWT Token',
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'username': {'type': 'string', 'description': '用户的登录名'},
                'password': {'type': 'string', 'description': '用户的登录密码'}
            },
            'required': ['username', 'password']
        }
    },
    responses={
        200: {
            'description': '登录成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'token': {'type': 'string'}
                    }
                }
            }
        },
        401: {
            'description': '用户名或密码错误'
        }
    },
    examples=[
        OpenApiExample(
            name='登录成功示例',
            value={
                'code': 200,
                'message': '登录成功',
                'data': {
                    'token': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xxxxx'
                }
            },
            response_only=True
        )
    ]
)
class LoginView(APIView):
    def post(self, request):
        try:
            data = json.loads(request.body)
            username = data.get('username')
            password = data.get('password')

            return UserService.login(username=username, password=password)

        except json.JSONDecodeError:
            return Response({
                "code": 400,
                "message": "请求体格式错误"
            }, status=400)

        except ValueError as e:
            return Response({
                "code": 401,
                "message": str(e)
            }, status=401)

        except Exception as e:
            logger.error(f"请求处理失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "message": "系统错误，请稍后再试"
            }, status=500)
@extend_schema(
    tags=['用户模块'],
    summary='手机号密码注册',
    description='通过手机号和密码注册新用户',
    request={
        'application/json': {
            'type': 'object',
            'properties': {
                'username': {'type': 'string', 'description': '用户的昵称'},
                'phone': {'type': 'string', 'description': '手机号（11位数字）'},
                'password': {'type': 'string', 'description': '明文密码'}
            },
            'required': ['username', 'phone', 'password']
        }
    },
    responses={
        201: {
            'description': '注册成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'user_id': {'type': 'string'},
                        'role': {'type': 'string'}
                    }
                }
            }
        },
        400: {
            'description': '手机号格式错误或已被注册'
        },
        500: {
            'description': '系统内部错误'
        }
    },
    examples=[
        OpenApiExample(
            name='注册成功示例',
            value={
                'code': 201,
                'message': '注册成功',
                'data': {
                    'user_id': 'abc123e4-5678-90ef-ghij-klmnopqrstuv',
                    'role': 'customer'
                }
            },
            response_only=True
        ),
        OpenApiExample(
            name='手机号已存在示例',
            value={'code': 400, 'message': '该手机号已被注册'},
            response_only=True
        )
    ]
)

class RegisterWithPhonePasswordView(APIView):
    def post(self, request):
        try:
            data = json.loads(request.body)
            username = data.get('username')
            phone = data.get('phone')
            password = data.get('password')

            result = UserService.register_with_phone(
                username=username,
                phone=phone,
                password=password,
            )
            return result

        except ValidationError as e:
            return Response({
                "code": 400,
                "message": str(e)
            }, status=400)

        except Exception as e:
            return Response({
                "code": 500,
                "message": "系统错误，请稍后再试"
            }, status=500)


class RegisterWithWeChatOpenIdView(APIView):
    def post(self, request):
        try:
            data = json.loads(request.body)
            wechat_openid = data.get('wechat_openid')
            phone = data.get('phone')
            username = data.get('username')

            result = UserService.register_with_wechat_openid(
                wechat_openid=wechat_openid,
                phone=phone,
                username=username
            )
            return result

        except ValidationError as e:
            return Response({
                "code": 400,
                "message": str(e)
            }, status=400)

        except Exception as e:
            return Response({
                "code": 500,
                "message": "系统错误，请稍后再试"
            }, status=500)
@extend_schema(
    tags=['用户模块'],
    summary='获取用户基本信息',
    description='根据用户ID获取用户的基本信息（不含敏感数据）',
    parameters=[
        {
            'name': 'user_id',
            'in': 'path',
            'description': '用户UUID',
            'required': True,
        }
    ],
    responses={
        200: {
            'description': '用户信息返回成功',
            'type': 'object',
            'properties': {
                'code': {'type': 'integer'},
                'message': {'type': 'string'},
                'data': {
                    'type': 'object',
                    'properties': {
                        'user_id': {'type': 'string', 'format': 'uuid'},
                        'username': {'type': 'string'},
                        'phone': {'type': 'string'},
                        'role': {'type': 'string'},
                        'created_at': {'type': 'string', 'format': 'date-time'}
                    }
                }
            }
        },
        404: {
            'description': '用户不存在'
        },
        500: {
            'description': '系统错误'
        }
    },
    examples=[
        OpenApiExample(
            name='获取用户信息成功示例',
            value={
                'code': 200,
                'message': '成功',
                'data': {
                    'user_id': 'abc123e4-5678-90ef-ghij-klmnopqrstuv',
                    'username': 'test_user',
                    'phone': '13800001111',
                    'role': 'customer',
                    'created_at': '2025-04-05T12:34:56Z'
                }
            },
            response_only=True
        ),
        OpenApiExample(
            name='用户不存在示例',
            value={'code': 404, 'message': '用户不存在'},
            response_only=True
        )
    ]
)
class GetUserInfoView(APIView):
    def get(self, request, user_id):
        """
        获取用户信息的接口
        URL 示例：/user/info/abc123e4-5678-90ef-ghij-klmnopqrstuv
        """
        try:
            return UserService.get_user_info(user_id)
        except Exception as e:
            return make_response(code=500, message="系统错误，请稍后再试")


from middleware.util import  AUTH_HEADER_PARAM

@extend_schema(
    tags=["用户模块"],
    summary="获取当前用户信息",
    parameters=[AUTH_HEADER_PARAM],
)
class CurrentUserInfoView(APIView):
    def get(self, request):
        """
        从 token 解析 user_id，获取当前用户信息
        URL 示例：/user/info/me/
        """
        user_id = request.user_id
        role = request.role
        if not user_id:
            return make_response(code=401, message="无效的 token 或 token 缺失")

        try:
            return UserService.get_user_info(user_id)
        except Exception as e:
            return make_response(code=500, message="系统错误，请稍后再试")
